package br.com.foxinline.servico;

import br.com.foxinline.generico.ServicoGenerico;
import br.com.foxinline.modelo.Endereco;
import br.com.foxinline.modelo.Imovel;
import br.com.foxinline.util.Caracter;
import java.util.Date;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
import javax.persistence.Query;

/**
 *
 * @author ely
 */
@Stateless
public class EnderecoServico extends ServicoGenerico<Endereco> {

    @EJB
    DneServico dneService;

    public EnderecoServico() {
        super(Endereco.class);
    }

    /**
     * <p>Verifica se existe algum endereço com o CEP informado</p>
     *
     * @param cep - String contendo o cep a ser pesquisado
     * @return <b>Address</b>, caso seja encontrado algum endereço, ou
     * <b>null</b>, caso contrário.
     */
    public Endereco existCep(Endereco a) {
        return dneService.existCep(a);
    }

    @Override
    public void save(Endereco endereco) {
        endereco.setCep(Caracter.removecaracter(endereco.getCep()));
        endereco.setCreateAt(new Date());
        super.save(endereco);
    }

    public Endereco findEnderecoImovel(Imovel imovel) {
        Endereco endereco;
        String sql = "Select e from Imovel i JOIN i.enderecoImovel e WHERE i.id = :im ";

        Query query = getEntityManager().createQuery(sql);

        query.setParameter("im", imovel.getId());

        System.out.println(sql);

        try {
            endereco = (Endereco) query.getResultList().get(0);

        } catch (NoResultException nr) {
            return null;
        } catch (NonUniqueResultException nre) {
            return null;
        } catch (Exception e) {
            return null;
        }
        return endereco;
    }
    
}
